package com.otaliastudios.cameraview.demo

import android.graphics.Bitmap
import android.graphics.Canvas
import android.graphics.Point
import android.os.Bundle
import android.os.Environment
import android.view.WindowManager
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.core.content.ContextCompat
import androidx.databinding.DataBindingUtil
import com.otaliastudios.cameraview.LogPlus
import com.otaliastudios.cameraview.demo.databinding.ActivityMjpegBinding
import com.otaliastudios.cameraview.entity.WarterMarkBean
import com.otaliastudios.cameraview.livedata.MarkMapLiveData
import com.otaliastudios.cameraview.livedata.RecordPauseLiveData
import java.io.File
import java.text.SimpleDateFormat
import java.util.*

class MjpegActivity : AppCompatActivity() {
    private lateinit var binding: ActivityMjpegBinding
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        window.setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN)
        window.setFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON, WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON)
        window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON)
        binding = DataBindingUtil.setContentView(this, R.layout.activity_mjpeg)
        binding.mjpegView.init("http://192.168.16.251:8080/?action=stream", this)

        val drawable = ContextCompat.getDrawable(this, R.drawable.ic_tiger)!!
        val bitmap = Bitmap.createBitmap(
            drawable.intrinsicWidth,
            drawable.intrinsicHeight,
            Bitmap.Config.ARGB_8888
        );
        val canvas = Canvas(bitmap);
        drawable.setBounds(0, 0, 100, 100);
        drawable.draw(canvas);
        MarkMapLiveData.get().value["PPPP"] = WarterMarkBean("PPPP", Point(200, 32 * 10), bitmap)

        binding.recordCb.setOnCheckedChangeListener { buttonView, isChecked ->
            if (isChecked) binding.mjpegView.record(saveVideoPath)
            else binding.mjpegView.stopRecord()
        }
        binding.pauseCb.setOnCheckedChangeListener { buttonView, isChecked ->
            RecordPauseLiveData.get().value = isChecked
            Toast.makeText(this, if (isChecked) "开始暂停" else "退出暂停", Toast.LENGTH_SHORT).show()
        }

    }

    val saveVideoPath: File
        get() {
            val format = SimpleDateFormat("yyyy-MM-dd HH:mm:ss")
            val time = format.format(Date())
            val file =
                File(Environment.getExternalStorageDirectory().path + "/test/live_save_video-" + time + ".avi")
            file.parentFile.mkdirs()
            return file
        }
}